package cn.yhjz.platform.system.util;

import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 操作redis的工具类
 */
@Component
public class RedisUtil {

    /**
     * 只保存String类型的数据，如果是对象就转成json字符串
     */
    @Autowired
    private StringRedisTemplate redisTemplate;

    public void set(String key, Object data, long timeout) {
        String dataString = JSON.toJSONString(data);
        this.set(key, dataString, timeout);
    }

    /**
     * 设置一个值
     *
     * @param key
     * @param data
     * @param timeout
     */
    public void set(String key, String data, long timeout) {
        redisTemplate.opsForValue().set(key, data, timeout, TimeUnit.SECONDS);
    }

    /**
     * 根据key获得值
     *
     * @param key
     * @return
     */
    public String get(String key) {
        ValueOperations<String, String> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }


    /**
     * 续期key的有效时间，单位秒
     *
     * @param key     key
     * @param timeout 超时时间，单位秒
     * @return true=成功 false:失败
     */
    public boolean expire(String key, long timeout) {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    public boolean expire(String key, long timeout, TimeUnit timeUnit) {
        return redisTemplate.expire(key, timeout, timeUnit);
    }

    /**
     * 判断 key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public Boolean has(String key) {
        return redisTemplate.hasKey(key);
    }
    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean delete(String key)
    {
        return redisTemplate.delete(key);
    }
}
